﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Telerik.WinControls.UI;
using log4net;
using System.Threading;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
namespace QuanLyNhaSach
{
    public partial class FormPhu_MatHang : Form
    {
        //Tao Parttern Seleton
        static FormPhu_MatHang doituong = null;
        sv_QuanLyNhaSach.AdapterClient service = new sv_QuanLyNhaSach.AdapterClient();
        private ILog logger;
        //string mamh, maloai, tenmh, nhasx, tacgia, namxb, dausach, dvt;
        //int soluongton;
        //float km;
        //byte[] hinh = null;
        //double gianhap, giasi, giale;
        public string mamh_fp;
        public string tt;
        public static FormPhu_MatHang TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new FormPhu_MatHang();
            return doituong;
        }

        public FormPhu_MatHang()
        {
            InitializeComponent();
        }
        private void FormPhu_MatHang_Load(object sender, EventArgs e)
        {
            //enter
            cmbdausach.KeyDown += new KeyEventHandler(cmbdausach_KeyDown);
            txttenhang.KeyDown += new KeyEventHandler(txttenhang_KeyDown);
            cmbdvt.KeyDown += new KeyEventHandler(cmbdvt_KeyDown);
            txtgianhap.KeyDown += new KeyEventHandler(txtgianhap_KeyDown);
            txtgiale.KeyDown += new KeyEventHandler(txtgiale_KeyDown);
            txtgiasi.KeyDown += new KeyEventHandler(txtgiasi_KeyDown);
            txtsldauky.KeyDown += new KeyEventHandler(txtsldauky_KeyDown);
            txtnxb.KeyDown += new KeyEventHandler(txtnxb_KeyDown);
            txtnsx.KeyDown += new KeyEventHandler(txtnsx_KeyDown);
            txtkm.KeyDown += new KeyEventHandler(txtkm_KeyDown);
            this.KeyDown += new KeyEventHandler(FormPhu_MatHang_KeyDown);
            //-----
            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            try
            {

                RadMultiColumnComboBoxElement multiColumnComboElement = this.cmbnhomhang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(300, 200);

                cmbdausach.Enabled = true;
                txtnsx.Enabled = true;
                txtnxb.Enabled = true;
                cmbnhomhang.Enabled = false;
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(service.selectqueryByText("select maloai,tenloai from LoaiHang where MaLoai like 'sa'")));
                if (ds.Tables.Count > 0)
                {
                    cmbnhomhang.DataSource = ds.Tables[0];
                    cmbnhomhang.DisplayMember = "tenloai";
                    cmbnhomhang.ValueMember = "maloai";
                }
                cmbdausach.SelectedIndex = 0;
                cmbdvt.SelectedIndex = 0;

                if (tt == "sua")
                {
                    radButton1.Enabled = false;
                    if (mamh_fp != "")
                    {
                        DataSet ds1 = new DataSet();
                        try
                        {
                            ds1.ReadXml(new StringReader(service.selectqueryByText("select MaMH,MaLoai,TenMH,DonGiaNhap,DonGiaSi,DonGiaLe,Khuyenmai,NhaSX,TacGia,NamXuatBan,DauSach,DVT,SoLuongDauKy,SoLuongHienCo from MatHang where MaMH ='" + mamh_fp + "'")));
                            if (ds1.Tables.Count > 0)
                            {
                                try
                                {
                                    byte[] hinh = service.Layhinh(mamh_fp.Trim());
                                    if (hinh != null)
                                    {
                                        hinh = (byte[])Decompress(hinh);
                                        pictureBox1.Visible = true;
                                        pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                                        pictureBox1.Image = Image.FromStream(new MemoryStream(hinh));
                                    }
                                    else
                                    {
                                        pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
                                        pictureBox1.Image = global::QuanLyNhaSach.Properties.Resources.close2;
                                    }
                                }
                                catch (Exception)
                                {
                                    pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
                                    pictureBox1.Image = global::QuanLyNhaSach.Properties.Resources.close2;
                                }
                                cmbnhomhang.Text = TenLoaiMH(ds1.Tables[0].Rows[0]["MaLoai"].ToString().Trim());
                                if (ds1.Tables[0].Rows[0]["MaLoai"].ToString().Trim() == "SA")
                                {
                                    rdbtn_MHKhac.Checked = false;
                                }
                                else
                                    rdbtn_MHKhac.Checked = true;
                                rdbtn_MHKhac.Enabled = false;
                                rdbtn_Sach.Enabled = false;
                                cmbdausach.Text = ds1.Tables[0].Rows[0]["DauSach"].ToString();
                                cmbdvt.Text = ds1.Tables[0].Rows[0]["DVT"].ToString();
                                txttenhang.Text = ds1.Tables[0].Rows[0]["TenMH"].ToString();
                                txtgianhap.Text = double.Parse(ds1.Tables[0].Rows[0]["DonGiaNhap"].ToString()).ToString("#,##0");
                                txtgiale.Text = double.Parse(ds1.Tables[0].Rows[0]["DonGiaLe"].ToString()).ToString("#,##0");
                                txtgiasi.Text = double.Parse(ds1.Tables[0].Rows[0]["DonGiaSi"].ToString()).ToString("#,##0");
                                txtnsx.Text = ds1.Tables[0].Rows[0]["NhaSX"].ToString();
                                txtnxb.Text = ds1.Tables[0].Rows[0]["NamXuatBan"].ToString();
                                txttacgia.Text = ds1.Tables[0].Rows[0]["TacGia"].ToString();
                                txtkm.Text = ds1.Tables[0].Rows[0]["Khuyenmai"].ToString();
                                txtsldauky.Text = ds1.Tables[0].Rows[0]["SoLuongDauKy"].ToString();
                                cmbnhomhang.Enabled = false;
                                cmbdausach.Enabled = false;
                            }
                        }
                        catch (Exception ex)
                        {
                            
                        }
                    }
                }



            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        void FormPhu_MatHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData== Keys.F5)
            {
                Luu();
            }
        }

        void txtkm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtnxb.Focus();
        }

        void txtnsx_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtnsx.Focus();
        }

        void txtnxb_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txttacgia.Focus();
        }

        void txtsldauky_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtkm.Focus();
        }

        void txtgiasi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtsldauky.Focus();
        }

        void txtgiale_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtgiasi.Focus();
        }

        void txtgianhap_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtgiale.Focus();
        }

        void cmbdvt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtgianhap.Focus();
        }

        void txttenhang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                cmbdvt.Focus();
        }

        void cmbdausach_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txttenhang.Focus();
        }
        private string TenLoaiMH(string maloai)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select tenloai from loaihang where maloai like'" + maloai + "%'")));
            if (ds.Tables.Count > 0)
            {
                return ds.Tables[0].Rows[0][0].ToString();
            }
            return "";
        }
        private void rdbtn_Sach_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdbtn_Sach.Checked == true)
                {
                    cmbdausach.Enabled = true;
                    txtnsx.Enabled = true;
                    txtnxb.Enabled = true;
                    txttacgia.Enabled = true;
                    cmbnhomhang.Enabled = false;

                    DataSet ds = new DataSet();
                    ds.ReadXml(new StringReader(service.selectqueryByText("select maloai,tenloai from LoaiHang where MaLoai like 'sa%'")));
                    if (ds.Tables.Count > 0)
                    {
                        cmbnhomhang.DataSource = ds.Tables[0];
                        cmbnhomhang.DisplayMember = "tenloai";
                        cmbnhomhang.ValueMember = "maloai";
                    }
                    cmbdausach.SelectedIndex = 0;

                }
                else
                {
                    cmbdausach.Enabled = false;
                    txtnsx.Enabled = false;
                    txtnsx.Text = "";
                    txtnxb.Enabled = false;
                    txtnxb.Text = "";
                    txttacgia.Enabled = false;
                    txttacgia.Text = "";
                    cmbnhomhang.Enabled = true;

                    DataSet ds = new DataSet();
                    ds.ReadXml(new StringReader(service.selectqueryByText("select maloai,tenloai from LoaiHang where MaLoai not like 'sa%'")));
                    if (ds.Tables.Count > 0)
                    {
                        cmbnhomhang.DataSource = ds.Tables[0];
                        cmbnhomhang.DisplayMember = "tenloai";
                        cmbnhomhang.ValueMember = "maloai";
                    }
                    cmbdausach.SelectedIndex = -1;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
            
        }
        KiemTraBatLoi batloi = new KiemTraBatLoi();
        byte[] hinh;
        private byte[] ConvertImageToByte(Image image)
        {
            System.IO.MemoryStream MS = new System.IO.MemoryStream();
            image.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
            return MS.ToArray();
        }
        private void btnluu_Click(object sender, EventArgs e)
        {
            Luu();
            
        }

        private void Luu()
        {
            errorProvider1.Clear();
            try
            {
                if (txttenhang.Text == "")
                {
                    errorProvider1.SetError(txttenhang, "Tên mặt hàng không được bỏ trống");
                    txttenhang.Focus();
                    return;
                }
                string mamh = xulyma();
                string maloai = cmbnhomhang.SelectedValue.ToString().Trim();
                double gianhap = 0;
                if (txtgianhap.Text.Trim() != "")
                    gianhap = double.Parse(txtgianhap.Text);
                double giasi = 0;
                if (txtgiasi.Text.Trim() != "")
                    giasi = double.Parse(txtgiasi.Text);
                double giale = 0;
                if (txtgiale.Text.Trim() != "")
                    giale = double.Parse(txtgiale.Text);
                int soluongdauki = 0;
                if (txtsldauky.Text.Trim() != "")
                    soluongdauki = int.Parse(txtsldauky.Text);
                float khuyenmai = 0;
                if (txtkm.Text.Trim() != "")
                    khuyenmai = float.Parse(txtkm.Text) / 100;

                hinh = ConvertImageToByte(pictureBox1.Image);
                hinh = Compress(hinh);
                if (hinh.Length > 15360)
                {
                    errorProvider1.SetError(radButton1, "Độ lớn hình phải nhỏ hơn 15KB");
                    return;
                }
                if (tt == "sua")
                {
                    if (MessageBox.Show("Bạn có thật sự muốn sửa mặt hàng này", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        service.selectqueryByText("update MatHang set TenMH=N'" + txttenhang.Text + "',DonGiaNhap=" + gianhap + ",DonGiaSi=" + giasi + ",DonGiaLe=" + giale + ",Khuyenmai=" + khuyenmai + ",NhaSX=N'" + txtnsx.Text + "',TacGia=N'" + txttacgia.Text + "',NamXuatBan=N'" + txtnxb.Text + "',DauSach=N'" + cmbdausach.Text + "',DVT=N'" + cmbdvt.Text + "',SoLuongDauKy=" + soluongdauki + " where MaMH='" + mamh_fp + "'");
                    }
                    MessageBox.Show("Lưu thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    rdbtn_Sach.Checked = true;
                    cmbdausach.SelectedIndex = 0;
                    cmbdvt.SelectedIndex = 0;
                    txttenhang.Text = "";
                    txtsldauky.Text = "";
                    txtgiale.Text = "";
                    txtgianhap.Text = "";
                    txtgiasi.Text = "";
                    txtkm.Text = "";
                    txtnsx.Text = "";
                    txtnxb.Text = "";
                    txttacgia.Text = "";
                    pictureBox1.Image = null;
                }
                else
                {
                    if (rdbtn_Sach.Checked == true)
                    {
                        if (MessageBox.Show("Bạn có thật sự muốn thêm mặt hàng này", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (!service.InsertMatHang(mamh, maloai, txttenhang.Text, gianhap, giasi, giale, khuyenmai, txtnsx.Text, txttacgia.Text, txtnxb.Text, cmbdausach.Text, cmbdvt.Text, soluongdauki, 0, hinh))
                            {
                                MessageBox.Show("Thêm thất bại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            else
                            {
                                MessageBox.Show("Thêm thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                txttenhang.Text = "";
                                txtsldauky.Text = "";
                                txtgiale.Text = "";
                                txtgianhap.Text = "";
                                txtgiasi.Text = "";
                                txtkm.Text = "";
                                txtnsx.Text = "";
                                txtnxb.Text = "";
                            }
                            //}
                        }
                    }
                    else
                    {

                        if (MessageBox.Show("Bạn có thật sự muốn thêm mặt hàng này", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (!service.InsertMatHang(mamh, maloai, txttenhang.Text, gianhap, giasi, giale, khuyenmai, txtnsx.Text, txttacgia.Text, txtnxb.Text, cmbdausach.Text, cmbdvt.Text, soluongdauki, 0, hinh))
                            {
                                MessageBox.Show("Thêm thất bại", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            else
                            {
                                MessageBox.Show("Thêm thành công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                txttenhang.Text = "";
                                txtsldauky.Text = "";
                                txtgiale.Text = "";
                                txtgianhap.Text = "";
                                txtgiasi.Text = "";
                                txtkm.Text = "";
                                txtnsx.Text = "";
                                txtnxb.Text = "";
                            }
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }
        private string xulyma()
        {
            DataSet ds_tam = new DataSet();
            string mamoi="";
            try
            {               
                string chuoi = cmbnhomhang.SelectedValue.ToString().Trim() + xulydausach();
                ds_tam.ReadXml(new StringReader(service.selectqueryByText("select top 1 * from MatHang where MaMH like '" + chuoi + "%' order by MaMH desc")));
                if (ds_tam.Tables.Count == 0)
                    mamoi = chuoi + "000001";
                else
                {
                    string matam = ds_tam.Tables[0].Rows[0][0].ToString();
                    if (chuoi.Length == 4)
                    {
                        string kituso = matam.Substring(4, 16).ToString();
                        int somoi = int.Parse(kituso) + 1;
                        mamoi = chuoi + somoi.ToString("000000");
                    }
                    else
                    {
                        string kituso = matam.Substring(2, 18).ToString();
                        int somoi = int.Parse(kituso) + 1;
                        mamoi = chuoi + somoi.ToString("000000");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
            return mamoi;
        }
        public byte[] Compress(object data)
        {
            BinaryFormatter _BinaryFormatter = new BinaryFormatter();
            MemoryStream _MemoryStream = new MemoryStream();

            // Serializes an object, or graph of connected objects, to the given stream.
            _BinaryFormatter.Serialize(_MemoryStream, data);
            var dataIn = _MemoryStream.ToArray();

            using (MemoryStream memory = new MemoryStream())
            {
                //  using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
                using (DeflateStream gzip = new DeflateStream(memory, CompressionMode.Compress))
                {
                    gzip.Write(dataIn, 0, dataIn.Length);
                    // gzip.Write();
                }
                return memory.ToArray();
            }
        }
        private object Decompress(byte[] gzip)
        {
            using (DeflateStream stream = new DeflateStream(new MemoryStream(gzip), CompressionMode.Decompress))
            {
                const int size = 4096;
                byte[] buffer = new byte[size];
                using (MemoryStream memory = new MemoryStream())
                {
                    int count = 0;
                    do
                    {
                        count = stream.Read(buffer, 0, size);
                        if (count > 0)
                        {
                            memory.Write(buffer, 0, count);
                        }
                    }
                    while (count > 0);
                    var dataOut = memory.ToArray();
                    MemoryStream _MemoryStreamb = new MemoryStream(dataOut);
                    BinaryFormatter _BinaryFormatterb = new BinaryFormatter();
                    // Serializes an object, or graph of connected objects, to the given stream.
                    return _BinaryFormatterb.Deserialize(_MemoryStreamb);
                }
            }
        }
        private string xulydausach()
        {
            if (cmbdausach.Text == "Sách giáo khoa")
            {
                return "GK";
            }
            else if (cmbdausach.Text == "Sách ngoại ngữ")
            {
                return "NN";
            }
            else if (cmbdausach.Text == "Sách CNTT")
            {
                return "CN";
            }
            else if (cmbdausach.Text == "Sách kinh tế")
            {
                return "KT";
            }
            else if (cmbdausach.Text == "Sách kĩ thuật")
            {
                return "KI";
            }
            else if (cmbdausach.Text == "Sách tiểu thuyết")
            {
                return "TT";
            }
            return "";
        }

        private void radButton7_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void bttimhinh_Click(object sender, EventArgs e)
        {
            try
            {
                
                openFileDialog1.Filter = "JPG|*.jpg|GIF|*.gif";
                
                if (openFileDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK)
                {                    
                    hinh =System.IO.File.ReadAllBytes(openFileDialog1.FileName);
                }
                pictureBox1.ImageLocation = openFileDialog1.FileName;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }


        }

        private void radPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void FormPhu_MatHang_Enter(object sender, EventArgs e)
        {

        }

        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        //private void getdata()
        //{
        //    mamh = xulyma();
        //    maloai=cmbnhomhang.SelectedValue.ToString();
        //    tenmh= txttenhang.Text;
        //    gianhap= double.Parse(txtgianhap.Text);
        //    giasi= double.Parse(txtgiasi.Text);
        //    giale= double.Parse(txtgiale.Text);
        //    km= float.Parse(txtkm.Text);
        //    nhasx = txtnsx.Text;
        //    tacgia= txttacgia.Text;
        //    namxb= txtnxb.Text;
        //    dausach= cmbdausach.SelectedText;
        //    dvt= cmbdvt.SelectedText;
        //    soluongton= int.Parse(txtslton.Text);
        //}

    }
}
